var getPixels = require("get-pixels");
var images = require("images");
var constVar = require('./constVar');
var fs = require('fs');
var path = require('path');

/**获取png非透明区域的信息
 ** getPixels 解析出来的数据是一个多维数据
 ** 通过 pixels.get(x,y,z) 获取某个像素点信息中的rgba的某个值
 ** 像素信息是从左往右，从上到下，从rgba，这样排列的
 ** x就是横向的第几个，映射到图片上就是图片的宽，这是第一维
 ** y就是纵向的第几个，映射到图片上就是图片的高，就是第二维
 ** z就是rgba数组中的第几个，就是第三维
 */
function getImageAlphaInfo(filePath){
    return new Promise((resolve,reject)=>{
        getPixels(filePath, function(err, pixels) {
            if(err) {
              console.log("Bad image path");
              reject('Bad image path');
              return;
            }
            //图片的宽
            let width = pixels.shape[0];
            //图片的高
            let height = pixels.shape[1];
            
            //图片中最上面非透明处的y值
            let up = 0;
            let isUpFind = false;
            let down = height;
            let left = width;
            let right = 0;
        
            for(let h=0;h<height;h++){
                for(let w=0;w<width;w++){
                    let alpha = pixels.get(w,h,3);
                    if(alpha==0) continue;
                    if(!isUpFind){
                        isUpFind = true;
                        up = h;
                    }
                    down = h;
                    if(w<left)
                        left = w;
                    if(w>right)
                        right = w;
                }
            }
            if(right<left){
                //所有像素点都为透明
                resolve(null);
            }else{
                resolve({
                    /**路径 */
                    filePath,
                    /**切出来图片的宽 */
                    width: right-left+1,
                    /**切出来图片的高 */
                    height: down-up+1,
                    /**剪切点x */
                    x: left,
                    /**剪切点y */
                    y: up,
                    /**距离原图中点的偏移x */
                    offsetX: left-width/2,
                    offsetY: up-height/2
                });
            }
        });
    });
}
/**打包一堆png为图集，生成的图集放在第一个文件的同目录下 */
async function pack(pngPathArr){
    let folder = path.dirname(pngPathArr[0]);
    let pngInfoArr = [];
    for(let i=0;i<pngPathArr.length;i++){
        let pngPath = pngPathArr[i];
        let info = await getImageAlphaInfo(pngPath);
        info&&pngInfoArr.push(info);
    }
    if(pngInfoArr.length==0){
        console.log(folder+':文件全是透明的');
        return;
    }
    //找到所有图片最大的宽，高
    let maxWidth = 0;
    let maxHeight = 0;
    pngInfoArr.forEach((ele)=>{
        if(ele.width>maxWidth)
            maxWidth = ele.width;
        if(ele.height>maxHeight)
            maxHeight = ele.height;
    });
    /**格子排版数 */
    let gridNum = Math.ceil(Math.sqrt(pngInfoArr.length));
    if(maxWidth*gridNum>2048){
        //宽超2048了
        gridNum--;
    }else if(maxHeight*Math.ceil(pngInfoArr.length/gridNum)>2048){
        //高超2048了
        gridNum ++;
    }
    /**当前横向index */
    let xIndex = 0;
    /**当前纵向index */
    let yIndex = 0;
    /**json数据 */
    let jsonDic = {};
    let image = images(maxWidth*gridNum,maxHeight*Math.ceil(pngInfoArr.length/gridNum));
    pngInfoArr.forEach((ele,index)=>{
        let pngInfo = ele;
        let x = xIndex*maxWidth;
        let y = yIndex*maxHeight;
        jsonDic[index] = {};
        jsonDic[index].x = x;
        jsonDic[index].y = y;
        jsonDic[index].width = pngInfo.width;
        jsonDic[index].height = pngInfo.height;
        jsonDic[index].offsetX = pngInfo.offsetX;
        jsonDic[index].offsetY = pngInfo.offsetY;
        if(xIndex+1==gridNum){
            yIndex ++;
            xIndex = 0;
        }else{
            xIndex ++;
        }
        image.draw(images(images(pngInfo.filePath),pngInfo.x,pngInfo.y,pngInfo.width,pngInfo.height),x,y);
    });
    fs.writeFileSync(path.join(folder,constVar.packName+'.json'),JSON.stringify(jsonDic,null,4));
    await new Promise((resolve,reject)=>{
        image.saveAsync(path.join(folder,constVar.packName+'.png'),(err)=>{
            if(err)
                reject(err.message);
            else{
                console.log(folder+':pack ok');
                resolve();
            }
        });
    });
}
module.exports = pack;